from rest_framework.authentication import BaseAuthentication
from rest_framework.response import Response
import jwt
from django.conf import settings
from rest_framework.exceptions import AuthenticationFailed


class JwtQueryParamsAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response({
                'code': 2000,
                'error': '登录成功之后才能访问'
            })

        try:
            payload = jwt.decode(token, settings.SECRET_KEY, ['HS256'])
        except jwt.exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({
                'code': 1003,
                'error': 'token已经失效'
            })
        except jwt.DecodeError:
            raise AuthenticationFailed({
                'code': 1003,
                'error': 'token认证失败'
            })
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({
                'code': 1003,
                'error': '非法的token'
            })

        # request.user -> payload
        # request.auth -> token
        return payload, token
